package snuvm.venus;

import snuvm.*;
import snuvm.util.*;
import java.util.ArrayList;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;
import java.beans.*;
	
/*
Copyright (c) 2009-2010,  Jeongho Nah, Gangwon Jo, Jaejin Lee

Developed by 
	Jeongho Nah (jeongho"at"aces.snu.ac.kr)
	Gangwon Jo (gangwon"at"aces.snu.ac.kr)
	Jaejin Lee (jlee"at"cse.snu.ac.kr)


Permission is hereby granted to use this version of the code 
under the same terms as MARS, which has the following license:

--
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson (psanderson"at"otterbein.edu)
and Kenneth Vollmar (kenvollmar"at"missouristate.edu)

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
 
    /**
    * Action  for the File -> Open menu item
    */   			
    public class FileOpenAction extends GuiAction {
    
      private File mostRecentlyOpenedFile;
      private JFileChooser fileChooser;
      private int fileFilterCount;
      private ArrayList fileFilterList;
      private PropertyChangeListener listenForUserAddedFileFilter;
   	 
       public FileOpenAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
         mostRecentlyOpenedFile = null;
         fileChooser = new JFileChooser();
         listenForUserAddedFileFilter = new ChoosableFileFilterChangeListener();
         fileChooser.addPropertyChangeListener(listenForUserAddedFileFilter);
      
      	// Note: add sequence is significant - last one added becomes default.
         fileFilterList = new ArrayList();
         fileFilterList.add(fileChooser.getAcceptAllFileFilter());
         fileFilterList.add(FilenameFinder.getFileFilter(Globals.fileExtensions, "Assembler Files", true));
         fileFilterCount = 0; // this will trigger fileChooser file filter load in next line
         setChoosableFileFilters();
      }
   	 
       /**
   	  * Launch a file chooser for name of file to open
   	  *
   	  * @param e component triggering this call
   	  */
       public void actionPerformed(ActionEvent e) {
         EditPane editPane = mainUI.getMainPane().getEditPane();
         if (!mainUI.editor.editsSavedOrAbandoned()) {
            return;
         }
      
         /* To get a slightly cleaner "look" in the environment of "only one file can be
      	 * open at a time", then do the fileCloseAction.actionPerformed() statements here.
      	 * It will reset the editing area, filename, and menu items.  It presents
      	 * a cleaner background for the file open dialog.  
      	 *
      	 * This feature is implemented by the following commented-out statement.  Activate
      	 * it by uncommenting and recompiling.  You also need to un-comment the 
      	 * getFileCloseAction() method in JSPIMUI class.
      	 */
         // mainUI.getFileCloseAction().actionPerformed(new ActionEvent(this,0,""));
      
         // The fileChooser's list may be rebuilt from the master ArrayList if a new filter
      	// has been added by the user.
         setChoosableFileFilters();
         /* get name of file to be opened and load contents into text editing area.
      	 */
         fileChooser.setCurrentDirectory(new File(editPane.getCurrentDirectoryPath()));
         // Set default to previous file opened, if any.  This is useful in conjunction
      	// with option to assemble file automatically upon opening.  File likely to have
      	// been edited externally (e.g. by Mipster).
         if (Globals.getSettings().getAssembleOnOpenEnabled() && mostRecentlyOpenedFile != null) {
            fileChooser.setSelectedFile(mostRecentlyOpenedFile);
         }
      
         if (fileChooser.showOpenDialog(editPane) == JFileChooser.APPROVE_OPTION) {
            File theFile = fileChooser.getSelectedFile();
            try {
               theFile = theFile.getCanonicalFile();
            } 
                catch (IOException ioe) {
               // nothing to do, theFile will keep current value
               }
            String currentFilePath = theFile.getPath();
            FileStatus.reset();
            FileStatus.setName(currentFilePath);
            FileStatus.setFile(theFile);
            if (theFile.canRead()) {
               Globals.program = new ARM9program();
               try {
                  Globals.program.readSource(currentFilePath);
               } 
                   catch (ProcessingException pe) {
                  }
               editPane.setSourceCode(null,true);
            	// DPS 1 Nov 2006.  Defined a StringBuffer to receive all file contents, 
            	// one line at a time, before adding to the Edit pane with one append.
            	// StringBuffer is preallocated to full filelength to eliminate dynamic
            	// expansion as lines are added to it. Previously, each line was appended 
            	// to the Edit pane as it was read, way slower due to dynamic string alloc.  
               StringBuffer fileContents = new StringBuffer((int)theFile.length());
               int lineNumber = 1;
               String line = Globals.program.getSourceLine(lineNumber++);
               while (line != null) {
                  fileContents.append(line+"\n");
                  line = Globals.program.getSourceLine(lineNumber++);
               }
               editPane.append(fileContents.toString());
               editPane.setCurrentDirectoryPath(fileChooser.getCurrentDirectory().getPath());
               editPane.setShowLineNumbersEnabled(true);
               FileStatus.setSaved(true);
               FileStatus.setEdited(false);
               mainUI.editor.setFrameTitle();
               editPane.getUndoManager().discardAllEdits();
               FileStatus.set(FileStatus.NOT_EDITED);
               mainUI.getMainPane().getExecutePane().clearPane();
               mainUI.getMainPane().setSelectedComponent(editPane);
               mostRecentlyOpenedFile = theFile;
                // possibly send this file right through to the assembler by firing Run->Assemble's
            	 // actionPerformed() method.
               if (Globals.getSettings().getAssembleOnOpenEnabled()) {
                  mainUI.getRunAssembleAction().actionPerformed(null);
               }
            }
         }
         
      	
      } 
   
      // Private method to generate the file chooser's list of choosable file filters.
   	// It is called when the file chooser is created, and called again each time the Open
   	// dialog is activated.  We do this because the user may have added a new filter 
   	// during the previous dialog.  This can be done by entering e.g. *.txt in the file
   	// name text field.  Java is funny, however, in that if the user does this then
   	// cancels the dialog, the new filter will remain in the list BUT if the user does
   	// this then ACCEPTS the dialog, the new filter will NOT remain in the list.  However
   	// the act of entering it causes a property change event to occur, and we have a
   	// handler that will add the new filter to our internal filter list and "restore" it
   	// the next time this method is called.  Strangely, if the user then similarly
   	// adds yet another new filter, the new one becomes simply a description change
   	// to the previous one, the previous object is modified AND NO PROPERTY CHANGE EVENT 
   	// IS FIRED!  I could obviously deal with this situation if I wanted to, but enough
   	// is enough.  The limit will be one alternative filter at a time.
   	// DPS... 9 July 2008
   	
       private void setChoosableFileFilters() {
         // See if a new filter has been added to the master list.  If so,
      	// regenerate the fileChooser list from the master list.
         if (fileFilterCount < fileFilterList.size() || 
             fileFilterList.size() != fileChooser.getChoosableFileFilters().length) {
            fileFilterCount = fileFilterList.size();
            // First, "deactivate" the listener, because our addChoosableFileFilter
            // calls would otherwise activate it!  We want it to be triggered only
            // by MARS user action.
            boolean activeListener = false;
            if (fileChooser.getPropertyChangeListeners().length > 0) {
               fileChooser.removePropertyChangeListener(listenForUserAddedFileFilter);
               activeListener = true;  // we'll note this, for re-activation later
            }
            // clear out the list and populate from our own ArrayList.
            // Last one added becomes the default.
            fileChooser.resetChoosableFileFilters();
            for (int i=0; i < fileFilterList.size(); i++) {
               fileChooser.addChoosableFileFilter((FileFilter)fileFilterList.get(i));
            }
            // Restore listener.
            if (activeListener) {
               fileChooser.addPropertyChangeListener(listenForUserAddedFileFilter);
            }
         }
      }//////////////////////////////////////////////////////////////////////////////////
   	//  Private inner class for special property change listener.  DPS 9 July 2008.
   	//  If user adds a file filter, e.g. by typing *.txt into the file text field then pressing
   	//  Enter, then it is automatically added to the array of choosable file filters.  BUT, unless you
   	//  Cancel out of the Open dialog, it is then REMOVED from the list automatically also. Here
   	//  we will achieve a sort of persistence at least through the current activation of MARS.
   	
       private class ChoosableFileFilterChangeListener implements PropertyChangeListener {
          public void propertyChange(java.beans.PropertyChangeEvent e) {
            if (e.getPropertyName()==JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY) {
               FileFilter[] newFilters = (FileFilter[]) e.getNewValue();
               FileFilter[] oldFilters = (FileFilter[]) e.getOldValue();
               if (newFilters.length > fileFilterList.size()) {
                  // new filter added, so add to end of master list.
                  fileFilterList.add(newFilters[newFilters.length-1]);
               }
            }
         }		
      }
   }      
